/*
 * @Author: suxunying
 * @desc: 
 * @Date: 2021-07-27 16:35:01
 * @LastEditors: suxunying
 * @LastEditTime: 2021-07-27 16:39:37
 * @FilePath: \bmp-poc\plat\src\utils\shared\utils.ts
 */
const hasOwn = Object.prototype.hasOwnProperty;

function is(x: any, y: any) {
    if (x === y) {
        return x !== 0 || y !== 0 || 1 / x === 1 / y
    } else {
        return x !== x && y !== y
    }
};

export function shallowEqual(objA: any, objB: any): boolean {
    if (is(objA, objB)) return true;

    if (typeof objA !== 'object' || objA === null ||
        typeof objB !== 'object' || objB === null) {
        return false
    }

    const keysA = Object.keys(objA)
    const keysB = Object.keys(objB)

    if (keysA.length !== keysB.length) return false

    for (let i = 0; i < keysA.length; i++) {
        if (!hasOwn.call(objB, keysA[i]) ||
            !is(objA[keysA[i]], objB[keysA[i]])) {
            return false
        }
    }

    return true
}

export function update(cacheState: any, newState: any): string {
    const keys = Object.keys(newState);
    for(let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if (!shallowEqual(cacheState[key], newState[key])) return key
    }
    return '';
}
